var path = require('path')
var webpack = require('webpack')
var VueLoaderPlugin = require('vue-loader/lib/plugin')
var CleanPlugin = require('clean-webpack-plugin')
var MiniCssExtractPlugin = require("mini-css-extract-plugin")
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin")
var shell = require('shelljs')


// 根据环境变量不同获取不同的配置文件
console.log(`当前环境：${process.env.BITGAME_env}`)

if (process.env.BITGAME_env == 'test') {
    shell.cp('-R', './src/config/test.env.js', './src/config/env.js')
}
else if (process.env.BITGAME_env == 'dev') {
    shell.cp('-R', './src/config/dev.env.js', './src/config/env.js')
}
else if (process.env.BITGAME_env == 'prod') {
    shell.cp('-R', './src/config/prod.env.js', './src/config/env.js')
}
else {
	//shell.cp('-R', './src/config/publish.env.js', './src/config/env.js')
    // 支持自定义环境，这点可能存在潜在的问题
    shell.cp('-R', `./src/config/${process.env.BITGAME_env}.env.js`, './src/config/env.js')
}

const resolvePath = (dir) => {
    return path.resolve(__dirname, dir)
}

var webpackConfig = {
    mode: 'production',
    // 指定spa应用的入口文件
    entry: {
        app: ["babel-polyfill", path.resolve(__dirname, 'src/main.js')],
        vendors: ['vue', 'vuex', 'vue-router', 'axios']
    },
    // 指定项目构建的输出位置
    output: {
        path: path.resolve(__dirname, 'dist'),
        // 框架基础js压缩包
        filename: './js/app_[hash:8].js',
        // 异步加载 -- 服务器目录分级
        publicPath: './',
        // 分块名称设置
        chunkFilename: './js/[name]_[chunkhash:8]_chunk.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        js: [
                            'babel-loader',
                        ],
                        css: 'style-loader!css-loader!postcss-loader',
                        scss: 'style-loader!css-loader!postcss-loader!sass-loader',
                        sass: 'style-loader!css-loader!postcss-loader!sass-loader'
                    }
                }
            },
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                include: [path.resolve(__dirname, "src"), path.resolve(__dirname, "test"), path.resolve(__dirname, "example")],
                use: [
                    {
                        loader: "babel-loader"
                    }
                ]
            },
            {
                test: /\.yaml$/,
                exclude: /node_modules/,
                loader: "yaml-loader",
            },
            // 处理在js中引用css文件
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'
                        }
                    },
                    //MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            // 处理在js中引用scss文件
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'
                        }
                    },
                    //MiniCssExtractPlugin.loader,
                    "css-loader",
                    "postcss-loader",
                    "sass-loader"
                ]
            },
            // 处理在js中引用less文件
            {
                test: /\.less$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'
                        }
                    },
                    //MiniCssExtractPlugin.loader,
                    "css-loader",
                    "postcss-loader",
                    "less-loader"
                ]
            },
            // 处理图片操作
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                //use: 'url-loader?limit=10240' //1K=1024字节 小于10k的写成base64
                use: 'url-loader?limit=10240&name=./images/[name]_[hash:8].[ext]'
            },
            // 处理字体文件
            {
                test: /\.(eot|woff|ttf|woff2|svg)$/,
                use: 'url-loader?limit=10000&name=./fonts/[name]_[hash:8].[ext]'
            },
            // 处理媒体文件
            {
                test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
                use: 'url-loader?limit=10000&name=./media/[name]_[hash:8].[ext]'
            },
            {
                test: /\.(csv|tsv)$/,
                use: [
                    'csv-loader'
                ]
            },
            {
                test: /\.xml$/,
                use: [
                    'xml-loader'
                ]
            }
        ]
    },
    externals: {
    },
    resolve: {
        extensions: ['.js', '.vue', '.json','.less'],
        alias: {
            '@': resolvePath('src'),
            '@asserts': resolvePath('src/asserts')
        }
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                default: {
                    minChunks: 2,
                    priority: -20,
                    reuseExistingChunk: true
                },
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    priority: 8,
                    chunks: 'all'
                },
                // libs: {
                //     test: /[\\/]node_modules[\\/]/,
                //     chunks: 'initial',
                //     priority: 9,
                //     name: 'vendors-libs',
                // },
                // asyncLibs: {
                //     test: /[\\/]node_modules[\\/]/,
                //     chunks: 'async',
                //     priority: 10,
                //     name: 'vendors-asynclibs'
                // },
                elementUI: {
                    name: 'vendors-elementUI', // 单独将 elementUI 拆包
                    test: /[\\/]node_modules[\\/]element-ui[\\/]/, // 规则
                    priority: 20, // 权重要大于 libs 和 app 不然会被打包进 libs 或者 app
                    chunks: 'all'
                },
                styles: {
                    name: 'app',
                    test: /\.css$/,
                    chunks: 'all',
                    enforce: true
                },
                manifest: {
                    name: 'manifest',
                    minChunks: Infinity
                },
            }
        },
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: true // set to true if you want JS source maps
            }),
            new OptimizeCSSAssetsPlugin({})
        ]
    },
    plugins: [

        // 删除文件夹的插件
        new CleanPlugin(['dist']),
        new CopyWebpackPlugin([
            { from: 'src/asserts/static', to: 'asserts/' },
            // { from: 'Dockerfile', to: './' },
            // { from: 'nginx.conf', to: './' }
        ]),
        new VueLoaderPlugin(),
        // 抽取样式文件的插件
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            // filename: "./css/[name]_[hash:8].css"
            filename: "./css/[name]_[hash:8].css"
            // chunkFilename: "[id].css"
        }),
        // 自动生成html插件
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './src/template.html',
            inject: true,
            // htmlWebpackPlugin: {
            //     "files": {
            //         // "css": ["app.css"],
            //         // "js": ["vendors.js", "bundle.js"]
            //         // "js": ["bundle.js"]
            //     }
            // },
            minify: {
                caseSensitive: true,
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                minifyCSS: true,
                minifyJS: true,
                preventAttributesEscaping: true,
                removeAttributeQuotes: true,
                removeComments: true,
                removeCommentsFromCDATA: true,
                removeEmptyAttributes: true,
                removeOptionalTags: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true,
                useShortDoctype: true
            }
        }),
        new webpack.LoaderOptionsPlugin({
            minimize: true
        }),
        // 压缩混淆js代码插件
        new UglifyJsPlugin({
            parallel: true,
            sourceMap: process.env.BITGAME_env != 'publish',
            uglifyOptions: {
                // ie8: false,
                //ecma: 8,
                mangle: {
                    // screw_ie8: true,
                    keep_fnames: true
                },
                output: {
                    comments: false,
                    beautify: false,
                    safari10: true,
                },
                compress: {
                    drop_debugger: true,
                    drop_console: process.env.BITGAME_env == 'publish'
                },
                //warnings: false
            }
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        })
    ]
}

module.exports = webpackConfig
